<template>
  <div class="page-layout">
    <el-alert title="草稿可作为模板继续使用也可在投保页选择 “投保并删除草稿”" type="warning" style="margin-bottom: 10px" :closable="false">
    </el-alert>
    <el-form :model="formInline" ref="form" label-width="90px" class="form-inline" label-suffix="：">
      <el-row :gutter="10">
        <el-col :lg="6" :xl="6"><el-form-item label="集装箱号">
            <el-input v-model="formInline.containerNumber" placeholder="请输入集装箱号"></el-input> </el-form-item></el-col>
        <!-- <el-col :lg="6" :xl="6"><el-form-item label="运单号">
            <el-input v-model="formInline.tagInvoiceWaybill" placeholder="请输入运单号"></el-input> </el-form-item></el-col> -->
        <el-col :lg="6" :xl="6">
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button :disabled="!multipleSelection.length" @click="payClick">支付</el-button>
        </el-col>
      </el-row>
    </el-form>
    <el-table ref="table" @selection-change="handleSelectionChange" border :data="tableData" :height="tableHeight" :style="{ width: '100%' }">
      <el-table-column type="selection" width="55" :selectable="checkSelectable">
      </el-table-column>
      <el-table-column prop="templateName" label="投保名称">
      </el-table-column>
      <el-table-column prop="containerNumber" label="集装箱号" width="140">
      </el-table-column>
      <!-- <el-table-column prop="tagInvoiceWaybill" label="运单号">
      </el-table-column> -->
      <el-table-column prop="insureFee" label="保费（元）" width="110">
      </el-table-column>
      <el-table-column prop="goodsName" label="货物名称">
      </el-table-column>
      <el-table-column prop="startTime" label="启运日期">
      </el-table-column>
      <el-table-column prop="startPlace" label="启运地">
      </el-table-column>
      <el-table-column prop="endPlace" label="目的地">
      </el-table-column>
      <el-table-column prop="endPlace" label="备注">
        <template slot-scope="scope">
          {{ aaa(scope.row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="150">
        <template slot-scope="scope">
          <el-button @click="viewClick(scope.row)" type="text" size="small">查看</el-button>
          <el-button @click="editClick(scope.row)" type="text" size="small">编辑</el-button>
          <el-button @click="deleteClick(scope.row)" type="text" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="支付" :visible.sync="payVisible" width="30%" :before-close="() => payVisible = false" v-loading="loading">
      <el-form :model="payForm" :rules="payRules" ref="payForm" label-width="110px" class="pay">
        <el-form-item label="支付总金额" prop="walletPassword">
          {{ totalFee() }}
        </el-form-item>
        <el-form-item label="支付密码" prop="walletPassword">
          <el-input placeholder="请输入支付密码" :maxlength="6" v-model="payForm.walletPassword" show-password></el-input>
        </el-form-item>
      </el-form>
      <p style="color:red">支付密码不是6位数字的客户，请在【管理中心】-【支付密码】中，尽快重新设置支付密码为6位数字</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="payVisible = false">取 消</el-button>
        <el-button type="primary" @click="payDetermine">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import moment from "moment";
const Decimal = require("decimal.js");
export default {
  computed: {
    aaa() {
      return (curTime) => {
        const yesterday = moment().subtract(1, "days").format("YYYY-MM-DD");
        if (curTime) {
          if (moment(curTime).isBefore(yesterday)) {
            return "启运日期，不能小于昨天，请编辑启运时间后再支付";
          } else {
            return "";
          }
        }
      };
    },
  },
  data() {
    return {
      loading: false,
      payVisible: false,

      payForm: {
        walletPassword: "",
      },

      pageSize: 10,
      total: 0,
      pageNum: 1,
      reverse: true,
      dialogVisible: false,
      tableHeight: 0,
      currentPage4: 4,
      isShow: false,
      formInline: {
        containerNumber: "",
        // tagInvoiceWaybill: ""
      },
      tableData: [],
      multipleSelection: [],
      payRules: {
        walletPassword: [
          { required: true, message: "请输入支付密码", trigger: "blur" },
        ],
      },
      goStatus: 1,
    };
  },
  methods: {
    totalFee() {
      // 使用 Decimal.js 计算属性 a 的和
      let sum = new Decimal(0);
      for (let item of this.multipleSelection) {
        sum = sum.plus(new Decimal(item.insureFee));
      }
      const price = sum.toString();
      return price + '元';
    },
    checkSelectable(row) {
      const yesterday = moment().subtract(1, "days").format("YYYY-MM-DD");
      if (row.startTime) {
        if (moment(row.startTime).isBefore(yesterday)) {
          return false;
        } else {
          return true;
        }
      }
    },
    payDetermine() {
      const warrantyDarftIds = [];
      this.multipleSelection.forEach((item) => {
        warrantyDarftIds.push(item.warrantyDarftId);
      });
      const params = {
        warrantyDarftIds,
        walletPassword: this.payForm.walletPassword,
        goStatus: this.goStatus,
      };
      this.$refs.payForm.validate((valid) => {
        if (valid) {
          if (this.loading) {
            return;
          }
          this.loading = true;
          this.$post("/warranty/darft/pay", params)
            .then((res) => {
              if (res && res.code * 1 === 200) {
                this.$message.success("支付成功");
                this.payForm.walletPassword = "";
                this.payVisible = false;
                this.getTableData();
              } else if (res && res.code * 1 === 500) {
                if (res.msg === "个人账户余额不足") {
                  this.$confirm(
                    "个人账户余额不足,请充值,充值后可在待支付里继续支付",
                    "提示",
                    {
                      confirmButtonText: "确定",
                      type: "warning",
                      showClose: false,
                      showCancelButton: false,
                    }
                  ).then(() => {
                    this.$router.push({
                      path: "/myWallet",
                    });
                  });
                } else {
                  this.payForm.walletPassword = "";
                }
              } else if (res && res.code * 1 === 9000) {
                if (res && res.code === 9000) {
                  this.$confirm(res.msg, "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                  })
                    .then(() => {
                      this.goStatus = 0;
                      this.payDetermine();
                    })
                    .catch(() => {
                      this.goStatus = 1;
                    });
                }
              }
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    payClick() {
      this.payVisible = true;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    deleteClick(row) {
      this.$toConfirm("是否确认删除", "warning", "提示")
        .then(() => {
          this.delConfirm(row);
        })
        .catch(() => {
          //
        });
    },
    delConfirm(row) {
      this.$post("/warranty/darft/remove", {
        warrantyDarftId: row.warrantyDarftId,
      }).then((res) => {
        if (res && res.code * 1 === 200) {
          this.$message.success("删除成功");
          this.getTableData();
        }
      });
    },
    viewClick(item) {
      this.$router.push({
        path: "/temp1",
        query: {
          warrantyDarftId: item.warrantyDarftId,
          insureInfoId: item.insureInfoId,
          templateName: item.templateName,
          isDetail: 1,
        },
      });
    },
    editClick(item) {
      this.$router.push({
        path: "/temp1",
        query: {
          warrantyDarftId: item.warrantyDarftId,
          insureInfoId: item.insureInfoId,
          templateName: item.templateName,
        },
      });
    },
    handleClose() {},
    trackClick() {},
    more() {
      this.isShow = !this.isShow;
      this.setTableHeight();
    },
    onSubmit() {
      this.pageNum = 1;
      this.getTableData();
    },
    handleSizeChange(val) {
      this.pageNum = 1;
      this.pageSize = val;
      this.getTableData();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getTableData();
    },
    setTableHeight() {
      this.$nextTick(() => {
        const bodyHeight = window.innerHeight;
        const queryHeight =
          this.$refs.form &&
          this.$refs.form.$el &&
          this.$refs.form.$el.offsetHeight;
        this.tableHeight = bodyHeight - queryHeight - 210 + "px";
      });
    },
    getTableData() {
      const params = {
        ...this.formInline,
      };
      this.$get("/warranty/darft/list", params).then((res) => {
        if (res) {
          this.tableData = res.data;
        } else {
          this.tableData = [];
        }
      });
    },
  },
  mounted() {
    this.setTableHeight();
    window.addEventListener("resize", this.setTableHeight);
    this.getTableData();
  },
};
</script>
<style scoped lang="less">
.time {
  /deep/.el-form-item__label {
    line-height: 20px;
  }
}
</style>